package com.sky.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.exception.ChangeEmployeeException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);


        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 进行md5加密，然后再进行比对
        password= DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }


    /**
     * 添加员工
     *
     * @param employeeDTO
     * @return
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        // 1.创建要添加的员工对象
        Employee employee = new Employee();
        // 2.复制员工对象
        BeanUtils.copyProperties(employeeDTO,employee);
        // 3.补充其他信息
            // 设置员工状态 (启用1 禁用0)
        employee.setStatus(StatusConstant.ENABLE);
            // 设置默认密码（加密形式）
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
            // 设置添加时间
/*        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
            // 设置添加操作用户
        Long id = BaseContext.getCurrentId(); // 获取当前登录员工的id
        log.info("执行当前添加员工的工作人员id为:{}",id);
        employee.setCreateUser(id);
        employee.setUpdateUser(id);*/

        // 4.插入用户
        int i=employeeMapper.insert(employee);
    }



    /**
     * 分页查询员工
     *
     * @param employeePageQueryDTO
     * @return PageResult
     */
    @Override
    public PageResult selectEmployeePage(EmployeePageQueryDTO employeePageQueryDTO) {
        // 1.创建PageHelper分页拦截对象 ,设置分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        // 2.查询mapper,根据用户名模糊查询
        List<Employee> employeeList = employeeMapper.selectEmployeePage(employeePageQueryDTO.getName());
        // 3.构使用 PageInfo 来获取分页信息
        PageInfo<Employee> pageInfo = new PageInfo<>(employeeList);
        // 构建分页对象
        PageResult pageResult = new PageResult();
        // 4.获取分页数据
        long total = pageInfo.getTotal();
        List<Employee> pageInfoList = pageInfo.getList();
        // 5.设置分页数据
        pageResult.setTotal(total);
        pageResult.setRecords(pageInfoList);

        return pageResult;
    }



    /**
     * 更新员工账号状态
     *
     * @param id
     * @return
     */
    @Override
    public void changeEmployeeStatus(long id,Integer status) {
        // 1.创建员工对象
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
/*                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())*/
                .build();
        // 2.修改当前员工的状态
        int i=employeeMapper.changeEmployeeStatus(employee);
        String s = employee.getStatus() == 1 ? "启用" : "禁用";
        if(i>0){
            log.info("修改用户{}成功！",s);
            return;
        }
        throw new ChangeEmployeeException();
    }


    /**
     * 根据员工id查询员工个人信息
     *
     * @param id
     * @return
     */
    @Override
    public Employee selectEmployeeById(long id) throws Exception {
        // 1.查询员工信息
        Employee employee = employeeMapper.selectEmployeeOneById(id);
        // 不显示密码
        employee.setPassword("******");
        // 2.非空判断
        if(ObjectUtil.isNull(employee)){
            throw new Exception("查询员工信息失败！");
        }
        log.info("查询员工员工信息成功！==》 员工 {}", employee);
        return employee;
    }

    /**
     * 更新员工信息
     *
     * @param employeeDTO
     * @return
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        // 1.构建员工对象
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
            // 设置公用参数
   /*     employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());*/
        // 2.更新员工信息
        int i=0;
        if(ObjectUtil.isNotNull(employee)){
            i=employeeMapper.update(employee);
        }

        // 2.成功判断
        if(i>0){
            return;
        }
        throw new RuntimeException();
    }
}
